package com.bestv.database.dao;

import com.bestv.database.vo.Program;
import com.bestv.database.vo.Series;
import com.bestv.utils.cache.MemcacheHelper;
import com.bestv.utils.database.DBConnectionManager;
import com.bestv.utils.database.JDBCHelper;

import java.sql.Connection;
import java.util.ArrayList;

/**
 * Created by Henry on 14-5-22.
 */
public class ProgramDao extends BaseDao<Program> {

    public Program findBySeriesCode(String seriesCode, Integer itemVersion, Integer hdsdType) {
        Series series = new Series();
        series.setMediaCode(seriesCode);
        String cacheMediaCodeKey = series.getCacheMediaCodeKey(itemVersion, hdsdType);
        Program program = (Program) MemcacheHelper.getInstance().getObject(cacheMediaCodeKey);
        if (program != null) return program.isValid() ? program : null;

        String sql = "SELECT * FROM program WHERE SeriesCode=? AND HdsdType=? AND HdsdType<=2 ORDER BY ItemVersion";
        Connection conn = DBConnectionManager.getSlaveConnection();
        ArrayList<Object> rs = JDBCHelper.executeQuery(conn, sql, Program.class, seriesCode, hdsdType);
        JDBCHelper.close(conn);

        program = new Program();
        for (int i = rs.size() - 1; i >= 0; i--) {
            program = (Program) rs.get(i);
            MemcacheHelper.getInstance().addObject(program.getCacheIdKey(), program);
            MemcacheHelper.getInstance().addObject(program.getCacheMediaCodeKey(), program);
            if (itemVersion == program.getItemVersion()) break;
        }

        MemcacheHelper.getInstance().addObject(cacheMediaCodeKey, program);
        return program.isValid() ? program : null;
    }
}
